package com.crm.system.service.impl.couponManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.couponManager.Coupon;
import com.crm.model.entity.couponManager.CouponIssued;
import com.crm.model.entity.couponManager.CouponProduct;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.couponManager.CouponQO;
import com.crm.model.vo.couponManager.CouponPayListVO;
import com.crm.model.vo.couponManager.CouponVO;
import com.crm.service.couponManager.ContractCouponDbService;
import com.crm.service.couponManager.CouponDbService;
import com.crm.service.couponManager.CouponIssuedDbService;
import com.crm.service.couponManager.CouponProductDbService;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.service.productManager.CustomerProductDbService;
import com.crm.system.service.couponManager.CouponService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author:chaifuyou
 * @Date: 2021/5/11 15:54
 */
@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponDbService couponDbService;

    @Autowired
    private CouponProductDbService couponProductDbService;

    @Autowired
    private CustomerMemberProductDbService customerMemberProductDbService;

    @Autowired
    private CustomerProductDbService customerProductDbService;

    @Autowired
    private CouponIssuedDbService couponIssuedDbService;

    @Autowired
    private ContractCouponDbService contractCouponDbService;

    /**
     * 优惠券分页列表
     * @param couponQO
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<CouponVO> selectFollowPlanList(CouponQO couponQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        List<CouponVO> productActivityVOList = couponDbService.selectFollowPlanList(couponQO,order.toString());
        PageInfo<CouponVO> pageInfo = new PageInfo<CouponVO>(productActivityVOList);
        return new DhPageInfo<CouponVO>(pageInfo, productActivityVOList);
    }

    /**
     * 新增优惠券
     * @param couponQO
     */
    @Override
    public boolean addCouponOrUpdateCoupon(CouponQO couponQO) {
        Coupon coupon = new Coupon();
        BeanUtils.copyProperties(couponQO, coupon);
        String couponId = couponQO.getChsCustomerCouponId();
        //查询是否有重名
        Integer count  =couponDbService.selectCountByNameAndId(couponId,coupon.getCouponName());
        if (StringUtils.isEmpty(couponId) && count > 0 ){
            return true;
        }
        if (Objects.isNull(coupon.getChsCustomerCouponId())){
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
            coupon.setChsCustomerCouponId("YH"+randomCode(6));//主键格式：YH+随机6位码
            coupon.setCreatePeopleId(userAccount.getAccountId());
            coupon.setCreateTm(new Date());
            coupon.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            coupon.setCouponStatus((short) 0);
            couponDbService.addCoupon(coupon);

            if(couponQO.getScopeOfApplication() == (short)1 || couponQO.getProductList().size() == 0){
                return false;
            }
        }else {
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
            coupon.setUpdatePeopleId(userAccount.getAccountId());
            coupon.setUpdateTm(new Date());

            if(couponQO.getProductList().size() == 0){
                return false;
            }else{
                //更新时需要把原分配产品删掉
                couponProductDbService.removeByCouponId(couponQO.getChsCustomerCouponId());
            }
            couponDbService.updateCoupon(coupon);
        }
        List<String> productList = couponQO.getProductList();
        List<CouponProduct> couponProducts = new ArrayList<>();
        for (String product : productList) {
            CouponProduct couponProduct = new CouponProduct();
            couponProduct.setCouponProductId(CommonUtils.getGUID());
            couponProduct.setCustomerProductId(product);
            couponProduct.setChsCustomerCouponId(coupon.getChsCustomerCouponId());
            couponProducts.add(couponProduct);
        }
        couponProductDbService.insertBatch(couponProducts);
        return false;
    }

    @Override
    public DhPageInfo<CouponVO> selectAvailableCouponPageList(CouponQO couponQO, Integer pageIndex, Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<CouponVO> productActivityVOList = couponDbService.selectAvailableCouponPageList(couponQO);
        PageInfo<CouponVO> pageInfo = new PageInfo<CouponVO>(productActivityVOList);
        return new DhPageInfo<CouponVO>(pageInfo, productActivityVOList);
    }

    @Override
    public Coupon selectCouponById(String couponId) {
        Coupon coupon = couponDbService.selectCouponById(couponId);
        return coupon;
    }

    @Override
    public CouponVO couponInfo(String couponId,String customerId) {
        Coupon coupon = couponDbService.selectCouponById(couponId);
        CouponVO couponVO = new CouponVO();
        BeanUtils.copyProperties(coupon, couponVO);

        if(StringUtils.isNotEmpty(customerId)){
            //客户详情页面进入
            //查询发放时间
            CouponIssued couponIssued = couponIssuedDbService.selectByCouponIdAndCustomerId(couponId, customerId);
            if(Objects.isNull(couponIssued)){
                return null;
            }
            couponVO.setIssuedTime(couponIssued.getCreateTm());

            if(couponIssued.getUsed() == (short) 1){ //该优惠券已使用
                //查询消费记录
                List<CouponPayListVO> customerContractCoupons = contractCouponDbService.selectContractCouponByCouponIdAndCustomerId(couponId, customerId);
                couponVO.setPayList(customerContractCoupons);
            }
        }

        if(1 == coupon.getScopeOfApplication()){
            return couponVO;
        }

        //产品包括会员产品和非会员产品，分别查询
        List<Map<String,String>> productIdList = couponProductDbService.selectProductIdListByCouponId(couponId);
        if(productIdList.size() > 0){

            List<Map<String,String>> customerMemberProducts = customerMemberProductDbService.selectMemberProductByIdList(productIdList);
            List<Map<String,String>> customerProducts = customerProductDbService.selectProductByIdList(productIdList);

            List<Map<String,String>> resultList = new ArrayList<Map<String,String>>();
            resultList.addAll(customerMemberProducts);
            resultList.addAll(customerProducts);

            couponVO.setProductNameList(resultList);
        }

        return couponVO;
    }

    /**
     * 获取随机码
     * @param len
     * @return
     */
    public String randomCode(int len){
        // 定义基本字符串baseStr和出参result
        String result = "";
        String baseStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        for (int i = 0; i < len; i++) {
            int rand = (int) (Math.random() * baseStr.length());
            result+=baseStr.charAt(rand);
        }
        return result;
    }

    @Override
    public DhPageInfo<CouponVO> availableCouponList(CouponQO couponQO, Integer pageIndex, Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<CouponVO> productActivityVOList = couponDbService.availableCouponList(couponQO);
        PageInfo<CouponVO> pageInfo = new PageInfo<CouponVO>(productActivityVOList);
        return new DhPageInfo<CouponVO>(pageInfo, productActivityVOList);
    }
}
